package com.hbt.android.kotlin.service

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
//import android.support.v4.content.LocalBroadcastManager
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.KeyEventDispatcher

/**
 * 运行时动态注册广播接收事件
 *
 * 不要在收到广播后进行任何耗时操作,因为在广播中是不允许开辟线程的,
 * 当onReceiver( )方法运行较长时间(超过10秒)还没有结束的话,那么程序会报错(ANR),
 * 广播更多的时候扮演的是一个打开其他组件的角色,比如启动Service,Notification提示, Activity等！
 */
class LearnBroadcastReceiverActivity: AppCompatActivity() {

    private val TAG = "LearnBroadcastReceiverActivity"

    private lateinit var myReceiver: LearnBroadcastReceiver

    @SuppressLint("LongLogTag")
    override fun onCreate(savedInstanceState: Bundle?) {
        Log.e(TAG, "onCreate ->")

        super.onCreate(savedInstanceState)

        myReceiver = LearnBroadcastReceiver()
        // 创建广播过滤器，指定只接收android.net.conn.CONNECTIVITY_CHANGE的广播事件
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(myReceiver, intentFilter)


        // 自定义静态广播
        val intent = Intent()
        intent.action = "com.hbt.android.kotlin.LEARN_BROADCAST_RECEIVER"
        intent.component = ComponentName(packageName, "com.hbt.android.kotlin.service.LearnBroadcastReceiver" )
        sendBroadcast(intent)


//        val intentFilter = IntentFilter()
//        intentFilter.addAction("com.hbt.android.kotlin.LEARN_BROADCAST_RECEIVER")
//        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter)
//        val intent = Intent()
//        intent.action = "com.hbt.android.kotlin.LEARN_BROADCAST_RECEIVER"
//        Handler().postDelayed(Runnable {
//            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
//        }, 10 * 1000)

    }


    @SuppressLint("LongLogTag")
    override fun onDestroy() {
        Log.e(TAG, "onCreate ->")
        super.onDestroy()
        unregisterReceiver(myReceiver)
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver)
    }
}